#import <Foundation/Foundation.h>
#import <objc/runtime.h>

#import "FWColorIconView.h"
#import "FWCommon.h"


@implementation FWColorIconView


@synthesize icon, color;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame])) {
        self.backgroundColor = [UIColor clearColor];
    }
    
    return self;
}

- (void)dealloc
{
    [icon release];
    [color release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Attribute access

- (void)setColor:(UIColor*)newColor
{
    if (color == newColor)
        return;
    
    if (newColor && color && [newColor isEqual:color])
        return;
    
    [newColor retain];
    [color release];
    color = newColor;
    
    [self setNeedsDisplay];
}

- (void)setIcon:(NSString*)newIcon
{
    if (icon == newIcon)
        return;
    
    if (newIcon && icon && [newIcon isEqualToString:icon])
        return;

    [newIcon retain];
    [icon release];
    icon = newIcon;
    
    [self setNeedsDisplay];
}

// ******************************************************************************************
#pragma mark -
#pragma mark Drawing

- (void)drawRect:(CGRect) rect
{
    if (icon) {
        UIImage* image = [UIImage imageWithContentsOfFile:icon];
        if (image != nil) {
            CGContextRef context = UIGraphicsGetCurrentContext();
            CGContextSaveGState(context);
            
            [image drawInRect:rect];
            
            [color set];
            CGContextSetBlendMode(context, kCGBlendModeSourceAtop);
            CGContextFillRect(context, rect);
            CGContextRestoreGState(context);
        }
        else
            XLog(@"LI:PICommon: Cannot find image %@", icon);
    }
}

@end
